package com.wyyz.dao.impl;

import com.wyyz.bean.Emp;
import com.wyyz.dao.EmpDao;
import com.wyyz.util.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class EmpDaoImpl  implements EmpDao {

    private int i;

    @Override
    public List<Emp> getAllEmp() {
        QueryRunner queryRunner = new QueryRunner(DbUtils.getDataSource());
        List<Emp> empList = null;
        try {
            empList = queryRunner.query("select * from emp", new BeanListHandler<Emp>(Emp.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return empList;
    }

    @Override
    public int addEmp(ArrayList arrayList) {
        try {
            QueryRunner qr = new QueryRunner(DbUtils.getDataSource());
            Object[] params = arrayList.toArray();
            i = qr.update("INSERT INTO emp(empno,ename,job,sal,hiredate,comm,deptno) VALUES(?,?,?,?,?,?,?)", params);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            return i;
        }
    }

    @Override
    public List<Emp> query(String ename) {
        QueryRunner queryRunner = new QueryRunner(DbUtils.getDataSource());
        List<Emp> empList = null;
        Object[] prams={"%"+ename+"%"};
        try {
            empList = queryRunner.query("select * from emp where ename like ?", new BeanListHandler<Emp>(Emp.class),prams);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return empList;
    }

    @Override
    public int upDate(int empno, ArrayList arrayList) {
        try {
            QueryRunner qr = new QueryRunner(DbUtils.getDataSource());
            arrayList.add(empno);
            Object[] params = arrayList.toArray();
            i = qr.update("UPDATE emp SET empno=?,ename=?,job=?,sal=?,hiredate=?,comm=?,deptno=? WHERE empno=?",params);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            return i;
        }
    }

    @Override
    public int delete(int empno) {
        try {
            QueryRunner qr = new QueryRunner(DbUtils.getDataSource());
            i = qr.update("DELETE FROM emp WHERE empno=?",empno);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            return i;
        }
    }

}
